package com.tedu07.lcl.filter;

import com.tedu07.lcl.entity.User;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


//urlPatterns = 配置需要拦截的请求地址,可配置多个
@WebFilter(filterName = "MyFilter",urlPatterns = {"/index.html","/"})
public class MyFilter implements Filter {
    //当过滤器销毁时,执行的方法
    public void destroy() {
    }

    //在客户端请求到Controller之前和之后,执行的方法
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("执行了过滤器");
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //得到session对象
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        if(user != null){
            chain.doFilter(req, resp);  //放行,允许执行Controller
        }
        else {
            response.sendRedirect("/login.html");
        }
    }

    //当过滤器初始化时,执行的方法
    public void init(FilterConfig config) throws ServletException {

    }

}
